import java.util.List;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Test {
    public ListNode addTwoNumbers(ListNode l1,ListNode l2){
        ListNode dummyHead = new ListNode(0);//创建新链表的虚拟节点
        ListNode curr = dummyHead;//新链表上的指针
        int carry = 0;//这是进位值

        while(l1 != null || l2 != null){
            int x = (l1 != null) ? l1.val : 0;
            int y = (l2 != null) ? l2.val : 0;
            int sum = carry + x + y;

            carry = sum / 10;//更新进位值
            curr.next = new ListNode(sum % 10);//指针后移并创建新节点
            curr = curr.next;

            if(l1 != null){
                l1 = l1.next;
            }
            if(l2 != null){
                l2 = l2.next;
            }
        }
        //处理可能存在的最高位进位
        if(carry > 0){
            curr.next = new ListNode(carry);
        }

        return dummyHead.next;
    }
}
